import Vue from 'vue'
import globalPopup from './index.vue'

class GlobalPopup {
  constructor(usePopups = []) {
    this.init(usePopups)
    this.popups = {}
  }

  init(usePopups) {
    if (!usePopups || !Array.isArray(usePopups) || usePopups.length === 0) return

    usePopups.forEach((item) => {
      const { name, component } = item
      Vue.component(name, component)
    })
  }

  show(params) {
    const { type = '', isMaskClick = true, success = () => {} } = params

    if (!type) {
      console.error('请输入弹窗类型')
      return
    }

    const Popup = Vue.extend(globalPopup)
    const popup = new Popup()
    this.popups[type] = popup.$mount()
    document.body.appendChild(this.popups[type].$el)
    this.popups[type].init({
      isMaskClick,
      childCompType: type
    })
    this.popups[type].show()
    this.popups[type].$nextTick(() => {
      success(this.popups[type].$refs.childComp)
    })
  }

  hide(type) {
    this.popups[type].hide()
    document.body.removeChild(this.popups[type].$el)
    this.popups[type].$destroy()
  }

  hideAll() {
    // 关闭所有弹窗
    for (let type in this.popups) {
      try {
        this.popups[type].hide()
        document.body.removeChild(this.popups[type].$el)
        this.popups[type].$destroy()
      } catch (error) {}
    }
  }
}

export default GlobalPopup
